package ro.ubbcluj.cs.damate.plugin;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.eclipse.ui.progress.UIJob;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import org.osgi.util.tracker.ServiceTracker;

import ro.ubbcluj.cs.damate.plugin.services.AuthenticationService;
import ro.ubbcluj.cs.damate.plugin.services.DamateMonitoringService;
import ro.ubbcluj.cs.damate.plugin.settings.DamateSettings;

/**
 * The activator class controls the plug-in life cycle
 */
public class DamateActivator extends AbstractUIPlugin implements IStartup {

	// The plug-in ID
	public static final String PLUGIN_ID = "ro.ubbcluj.cs.damate.plugin"; //$NON-NLS-1$

	// The shared instance
	private static DamateActivator plugin;
	
	private ServiceRegistration monitoringServiceRegistration;
    private ServiceRegistration authenticationServiceRegistration;

	private ServiceTracker monitoringServiceTracker;
    private ServiceTracker authenticationServiceTracker;

	private DamateSettings settings;

	private BundleContext context;

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext)
	 */
	public void start(BundleContext bundleContext) throws Exception {
		super.start(bundleContext);
		plugin = this;
		this.context = bundleContext;
		this.settings = new DamateSettings();
		
		final DamateMonitoringService monitoringService = new DamateMonitoringService();
        final AuthenticationService authenticationService = new AuthenticationService();
				
		getPreferenceStore().addPropertyChangeListener(new IPropertyChangeListener() {
			public void propertyChange(PropertyChangeEvent event) {
				if (DamateSettings.CAPTURE_ENABLED_KEY.equals(event.getProperty())) {
					if (isTrue(event.getNewValue())) {
                        monitoringService.startMonitoring();
					} else {
                        monitoringService.stopMonitoring();
					}
				}
			}

			private boolean isTrue(Object newValue) {
				if (newValue instanceof Boolean) return ((Boolean)newValue).booleanValue();
				if (newValue instanceof String) return Boolean.valueOf((String)newValue);
				return false;
			}			
		});
		
		
		this.monitoringServiceRegistration = context.registerService(DamateMonitoringService.class.getName(), monitoringService, null);
        this.authenticationServiceRegistration = context.registerService(AuthenticationService.class.getName(), authenticationService, null);
		
		this.monitoringServiceTracker = new ServiceTracker(context, DamateMonitoringService.class.getName(), null);
        this.authenticationServiceTracker = new ServiceTracker(context, AuthenticationService.class.getName(), null);
        monitoringServiceTracker.open();
        authenticationServiceTracker.open();
		
		UIJob job = new UIJob("Damate Monitoring Service Starter") {
			public IStatus runInUIThread(IProgressMonitor monitor) {
				if (settings.isEnabled()) {
                    monitoringService.startMonitoring();
				}
				return Status.OK_STATUS;
			}
			
		};
		job.schedule(1000);		
		System.out.println("Plugin started...");
	}	

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext)
	 */
	public void stop(BundleContext context) throws Exception {
		plugin = null;
		super.stop(context);
		this.context = context;
		DamateMonitoringService service = getDamateMonitoringService();
		if (service != null) service.stopMonitoring();
		
		monitoringServiceTracker.close();
		monitoringServiceRegistration.unregister();
        authenticationServiceTracker.close();
        authenticationServiceRegistration.unregister();
		System.out.println("Plugin stoped...");
	}
	
	private DamateMonitoringService getDamateMonitoringService() {
		return (DamateMonitoringService)monitoringServiceTracker.getService();
	}

    public AuthenticationService getAuthenticationService() {
        return (AuthenticationService)authenticationServiceTracker.getService();
    }

	/**
	 * Returns the shared instance
	 *
	 * @return the shared instance
	 */
	public static DamateActivator getDefault() {
		return plugin;
	}
	
	public DamateSettings getSettings() {
		return settings;
	}

	public BundleContext getContext() {
		return context;
	}

	/**
	 * Returns an image descriptor for the image file at the given
	 * plug-in relative path
	 *
	 * @param path the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}

	@Override
	public void earlyStartup()
	{
		// TODO Auto-generated method stub
	}

    public static void log(String message , int status, Throwable e){
        getDefault().getLog().log(new Status(status, PLUGIN_ID, message, e));
    }
}
